// pages/sharemessage.js
import util from '../../utils/util.js';

/** 
 *字符串转json 
 */
function jsonToString(data) {
  return JSON.stringify(data);
}
/** 根据计划id获取所有共享成员 */
function getPartnerByPlanId(obj, planId) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })

  wx.request({
    url: getApp().globalData.url + '/PLanAndTask/getPartnerByPlanId',
    data: util.json2Form({
      "planId": planId,
    }),
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      wx.hideToast();
      var membersTemp = new Array();
      var isJoinedTemp = false;

      if (res.data.length<=0){
        /**先插入一条邀请人自己 */
        membersTemp.push({
          avatarUrl: obj.data.fromAvatarUrl,
          nickName: obj.data.fromUserName
        })
      }
    
      for (var i = 0; i < res.data.length; i++) {
        if (res.data[i].user_id == wx.getStorageSync("userId")) {
          isJoinedTemp = true;
        }

        membersTemp.push({
          avatarUrl: res.data[i].avatar_url,
          nickName: res.data[i].user_name
        })
      }

      obj.setData({
        members: membersTemp,
        isJoined: isJoinedTemp
      })
    }
  })
}

function updateUserAvatar(avatarUrl) {
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true
  })

  wx.request({
    url: getApp().globalData.url + '/loginMain/updateUserAvatar',
    data: util.json2Form({
      "userId": wx.getStorageSync("userId"),
      "avatarUrl": avatarUrl,
      "nickName": wx.getStorageSync("nickName")
    }),
    method: 'POST',
    header: {
      // 'Content-Type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      wx.hideToast();
    }
  })
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isJoined: false,
    isScope: false,
    fromAvatarUrl: "",
    fromUserId: "",
    fromUserName: "",
    planName: "",
    planId: "",
    members: [{
      avatarUrl: "",
      nickName: "111"
    }]
  },
  joinPLan: function(e) {
    var obj = this;
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })

    wx.request({
      url: getApp().globalData.url + '/PLanAndTask/addUserToPlan',
      data: util.json2Form({
        "user_id": wx.getStorageSync("userId"),
        "user_name": wx.getStorageSync("nickName"),
        "avatar_url": wx.getStorageSync("avatarUrl"),
        "plan_id": obj.data.planId,
        "fromUserId": obj.data.fromUserId,
        "fromUserName": obj.data.fromUserName,
        "from_avatar_url": obj.data.fromAvatarUrl
      }),
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideToast();

        wx.redirectTo({
          url: '../index/index',
        })
      }
    })
  },
  toIndex:function(e){
    wx.redirectTo({
      url: '../index/index',
    })
  },
    /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var obj = this;
    obj.setData({
      fromAvatarUrl: options.avatarUrl,
      fromUserName: options.nickName,
      planName: options.planName,
      planId: options.planId,
      fromUserId: options.userId
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    var obj = this;

    // 查看是否授权
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
              wx.setStorageSync("nickName", res.userInfo.nickName);
              wx.setStorageSync("avatarUrl", res.userInfo.avatarUrl);
              updateUserAvatar(res.userInfo.avatarUrl);

              obj.setData({
                isScope: true
              })
            },
            fail: function(e) {
              console.log(e);
              obj.setData({
                isScope: false
              })
            }
          })
        } else {
          obj.setData({
            isScope: false
          })
        }
      }
    })
    //判断是否已经授权登陆
    if (!wx.getStorageSync("isScope") || wx.getStorageSync("userId") == "") {
      wx.navigateTo({
        url: '../scope/scope',
      })
    } else {
      getPartnerByPlanId(obj, obj.data.planId);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})